<script setup>
import { ElMessage } from 'element-plus'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getCouponAPI } from '@/apis/coupon'
import { payCouponAPI } from '@/apis/coupon'
const now = ref(Date.now())
const getCoupon = async () => {
    const res = (await getCouponAPI()).data
    coupons.value = res.secKillCoupon
    commonCoupons.value = res.commonCoupon
}
onMounted(() => getCoupon())
// 使用类型映射
const useTypeMap = {
    0: '全场通用',
    1: '指定分类',
    2: '指定商品'
}

const coupons = ref([])
const commonCoupons = ref([])

let timer = null

onMounted(() => {
    timer = setInterval(() => {
        now.value = Date.now()
        updateCouponsStatus()
    }, 1000)
})

onBeforeUnmount(() => {
    clearInterval(timer)
})

// 转换时间方法
const parseTime = (timeStr) => {
    return new Date(timeStr).getTime()
}

// 新增方法：格式化显示日期
const formatDate = (timeStr) => {
    const date = new Date(timeStr)
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

const updateCouponsStatus = () => {
    coupons.value.forEach(coupon => {
        const start = parseTime(coupon.startTime)
        const activityEnd = start + coupon.duration * 1000 // 转为毫秒

        if (now.value < start) {
            coupon.status = 'pending'
        } else if (now.value >= start && now.value <= activityEnd) {
            coupon.status = coupon.remaining > 0 ? 'active' : 'sold-out'
        } else {
            coupon.status = 'ended'
            if (coupon.remaining <= 0) coupon.status = 'sold-out'
        }
    })
}

const timeDisplay = (coupon) => {
    const start = parseTime(coupon.startTime)
    const activityEnd = start + coupon.duration * 1000

    if (coupon.status === 'pending') {
        const diff = start - now.value
        return `距开始 ${formatTime(diff)}`
    }
    if (coupon.status === 'active') {
        const diff = activityEnd - now.value
        return `距结束 ${formatTime(diff)}`
    }
    return '已结束'
}
const formatTime = (ms) => {
    const seconds = Math.floor(ms / 1000)
    const h = Math.floor(seconds / 3600)
    const m = Math.floor((seconds % 3600) / 60)
    const s = seconds % 60
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

const soldPercentage = (coupon) => {
    return Math.round((coupon.count - coupon.remaining) / coupon.count * 100)
}
var flag = 0
const handleBuy = async (coupon) => {
    if (coupon.perLimit == 1 && flag == 1) {
        return
    }
    if (coupon.remaining > 0) {
        const res = (await payCouponAPI(coupon.id)).data
        //发送请求
        if (res) {
            coupon.remaining--
            ElMessage.success('恭喜领取成功！')
            flag++
        } else {
            throw new Error()
        }
        if (coupon.remaining === 0) {
            coupon.status = 'sold-out'

        }
    }
}

const canBuy = (coupon) => {
    return coupon.status === 'active' && coupon.remaining > 0
}

const buttonText = (status) => {
    return {
        'pending': '未开始',
        'active': '立即领取',
        'ended': '已结束',
        'sold-out': '已领完'
    }[status]
}

const buttonType = (status) => {
    return status === 'active' ? 'danger' : 'info'
}

const timeTagType = (status) => {
    return {
        'pending': 'warning',
        'active': 'success',
        'ended': 'info',
        'sold-out': 'danger'
    }[status]
}

const progressStatus = (coupon) => {
    if (coupon.remaining <= 0) return 'exception'
    return coupon.status === 'active' ? 'success' : 'warning'
}
const payCoupon = async (id) => {
    // window.location.href = "http://localhost:8080/pay/alipay?number="+number
    //向user_coupon表插入数据
    ElMessage.success('购买成功！')
}
</script>
<template>
    <div class="coupon-container">
        <h2 class="title"><img
                src="https://tse4-mm.cn.bing.net/th/id/OIP-C.wbA7l_-j2DrLStGBgw0fQQHaF7?w=231&h=184&c=7&r=0&o=5&dpr=1.3&pid=1.7"
                alt="皇冠" style="height: 25px;width: 25px;margin-bottom: 5px;">限时优惠券抢购</h2>
        <div class="coupon-list">
            <el-card v-for="coupon in coupons" :key="coupon.id" class="coupon-item"
                :class="{ 'sold-out': coupon.status === 'sold-out' }">
                <div class="coupon-content">
                    <div class="header">
                        <h3 class="name">{{ coupon.name }}</h3>
                    </div>

                    <div class="main-content">
                        <div class="left">
                            <div class="amount">
                                <span class="currency">¥</span>
                                <span class="value">{{ coupon.amount }}</span>
                            </div>
                            <div class="condition">
                                {{ coupon.minPoint === 0 ? '无使用门槛' : `满${coupon.minPoint}元可用` }}
                            </div>
                            <div class="validity">
                                有效期至：{{ formatDate(coupon.endTime) }}
                            </div>
                            <div class="use-range">
                                {{ useTypeMap[coupon.useType] }}
                            </div>
                        </div>

                        <div class="right">
                            <div class="time-remaining">
                                <el-tag :type="timeTagType(coupon.status)" size="large">
                                    {{ timeDisplay(coupon) }}
                                </el-tag>
                            </div>

                            <el-progress :percentage="soldPercentage(coupon)" :status="progressStatus(coupon)"
                                class="progress" />

                            <div class="operation">
                                <el-button :type="buttonType(coupon.status)" :disabled="!canBuy(coupon)"
                                    @click="handleBuy(coupon)" class="buy-btn">
                                    {{ buttonText(coupon.status) }}
                                </el-button>
                                <div class="remaining">剩余 {{ coupon.remaining }} 张</div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
        <h2 class="title"><img
                src="https://tse4-mm.cn.bing.net/th/id/OIP-C.wbA7l_-j2DrLStGBgw0fQQHaF7?w=231&h=184&c=7&r=0&o=5&dpr=1.3&pid=1.7"
                alt="皇冠" style="height: 25px;width: 25px;margin-bottom: 5px;">通用优惠劵购买</h2>
        <div class="coupon-list">
            <el-card class="coupon-item" v-for="coupon in commonCoupons" :key="coupon.id">
                <div class="coupon-content">
                    <div class="header">
                        <h3 class="name">{{ coupon.name }}</h3>
                    </div>

                    <div class="main-content">
                        <div class="left">
                            <div class="amount">
                                <span class="currency">¥</span>
                                <span class="value">{{ coupon.amount }}</span>
                            </div>
                            <div class="condition">
                                {{ coupon.minPoint === 0 ? '无使用门槛' : `满${coupon.minPoint}元可用` }}
                            </div>
                            <div class="validity">
                                有效期至：{{ coupon.note }}
                            </div>
                            <div class="use-range">
                                {{ useTypeMap[coupon.useType] }}
                            </div>
                        </div>
                        <div class="right">
                            <div class="time-remaining">
                                <el-tag size="large">开始</el-tag>
                            </div>
                            <el-divider border-style="solid" style="margin: 20px 0;" />
                            <div class="operation">
                                <el-button class="buy-btn" type="danger" @click="payCoupon(coupon.id)">
                                    ¥{{ coupon.price }}购买
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.coupon-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;

    .title {
        text-align: center;
        color: #FFDF00;
        font-weight: bolder;
        margin-bottom: 30px;
    }
}

.coupon-list {
    display: grid;
    gap: 20px;
}

.coupon-item {
    transition: all 0.3s;

    &.sold-out {
        opacity: 0.6;
        filter: grayscale(0.8);
    }

    .coupon-content {
        padding: 20px;

        .header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;

            .name {
                margin: 0;
                font-size: 18px;
                color: #333;
            }
        }

        .main-content {
            display: flex;

            .left {
                flex: 0 0 35%;
                border-right: 2px dashed #ddd;
                padding-right: 20px;
                text-align: center;

                .amount {
                    color: #f56c6c;

                    .currency {
                        font-size: 24px;
                    }

                    .value {
                        font-size: 48px;
                        font-weight: bold;
                    }
                }

                .condition {
                    color: #666;
                    margin: 8px 0;
                }

                .use-range {
                    color: #999;
                    font-size: 12px;
                }
            }

            .right {
                flex: 1;
                padding-left: 20px;

                .time-remaining {
                    margin-bottom: 15px;
                    text-align: center;
                }

                .progress {
                    margin: 20px 0;
                }

                .operation {
                    text-align: center;

                    .buy-btn {
                        width: 80%;
                        font-size: 16px;
                        padding: 12px;
                    }

                    .remaining {
                        margin-top: 8px;
                        color: #666;
                        font-size: 12px;
                    }
                }
            }
        }
    }
}

.validity {
    color: #999;
    font-size: 12px;
    margin-top: 8px;
}

@media (max-width: 768px) {
    .main-content {
        flex-direction: column !important;

        .left {
            border-right: none !important;
            border-bottom: 2px dashed #ddd;
            padding-right: 0 !important;
            padding-bottom: 20px;
            margin-bottom: 20px;
        }
    }
}
</style>